package org.houor.office.word;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * Word FreeMarker Utility
 * 
 * @author Houor
 *
 * @createTime 2017-04-01 22:10
 */
public class FreeMarkerDocumentHandler {

	private Configuration configuration = null;

	public FreeMarkerDocumentHandler(String templatebasePackagePath) {
		// create Configuration instance and specify FreeMarker version
		configuration = new Configuration(Configuration.VERSION_2_3_26);
		// Set the preferred charset template files are stored in.
		configuration.setDefaultEncoding("utf-8");
		// Specify the source where the template files come from
		configuration.setClassForTemplateLoading(this.getClass(), templatebasePackagePath);
	}

	public void generateDocument(Map<String, Object> dataMap, String templateName, String fileName) throws UnsupportedEncodingException {

		Template template = null;
		try {
			template = configuration.getTemplate(templateName);
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 输出文档路径及名称
		File outFile = new File(fileName);
		Writer out = null;
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(outFile);
			OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fos, "UTF-8");
			out = new BufferedWriter(outputStreamWriter);
		} catch (FileNotFoundException fnfe) {
			fnfe.printStackTrace();
		}

		try {
			template.process(dataMap, out);
			out.close();
			fos.close();
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}